<?php
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Redis;
use App\Libs\WxSmallClient;
/**
 * 全局自定义函数
 */
define("TO_URL",json_encode(
    [
        'qujia_getuser'=>'https://vip.jaxcx.com/api/queryByUid'
        //'qujia_getuser'=>'https://reg-uat.jaxcx.com/api/queryByUid'
    ]
));

// pVI6xjp6QqrJFgWC_tGkcQEDNz1w原味圆筒 = 麦香鱼汉堡 = 那么大鸡翅 = 双层吉士汉堡
define("ACT_CARD_ID", json_encode(['pVI6xjn20-qY_C3-zycogw1YWoF4', 'pVI6xjhDl4uDY72irnqIflvaXYaA', 'pVI6xjk0p16nDakQ7ivq-bvHVGM4', 'pVI6xjuNETcjqXpTRnFrw4_Ipf5E']));

 if (! function_exists('get_time')) {
    /**
     * Flatten a multi-dimensional array into a single level.
     *
     * @param  array  $array
     * @param  int  $depth
     * @return array
     */
    function get_time()
    {
        echo time();
    }
}

if (! function_exists('get_freight')) {
    /**
     * Flatten a multi-dimensional array into a single level.
     *
     * @param  array  $array
     * @param  int  $depth
     * @return array
     */
    function get_freight()
    {
        return 7;
    }
}



if (! function_exists('judge_price')) {
    /**
     * 递归创建目录
     */
    function judge_price($price)
    {
        //判断价格
        $rule  = "/^[1-9]\\d*$/";
        $result = preg_match($rule,$price);

        $rule  = "/^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$/";
        $results = preg_match($rule,$price);
        if(!$result && !$results){
            return false;
        }
    }
}

if (! function_exists('mkDirs')) {
    /**
     * 递归创建目录
     */
    function mkDirs($dir)
    {
        if ( !is_dir($dir) ) {
            if ( !mkDirs(dirname($dir)) ) {
                return false;
            }
            if ( !mkdir($dir,0777) ) {
                return false;
            }
        }
        return true;
    }
}

if (! function_exists('fun_respon')) {
    /**
     *  return json maxed
     */
    function fun_respon($success, $res = [], $code = 200)
    {
        $result['result'] = $success;

        if ($success == 400) {
            $result['result'] = 400;
            $result['msg'] = $res;
            $result['code'] = $code;
        } elseif ($success == 1) {
            $result['result'] = 1;
            $result['msg'] = '操作成功';
            $result['data'] = $res;
            $result['code'] = 200;
        } else {
            $result['result'] = 0;
            $result['msg'] = $res;
            $result['code'] = $code;
        }
        //header("Content-Type: application/ json; charset=UTF-8");
        exit(json_encode($result));
    }
}

if (! function_exists('ajax_respon')) {
    /**
     *  return json maxed
     */
    function ajax_respon($success, $res = [], $code = 200)
    {
        $result['result'] = $success;

        if ($success == 400) {
            $result['result'] = 400;
            $result['msg'] = $res;
            $result['code'] = $code;
        } elseif ($success == 1) {
            $result['result'] = 1;
            $result['msg'] = '操作成功';
            $result['data'] = $res;
            $result['code'] = 200;
        } else {
            $result['result'] = 0;
            $result['msg'] = $res;
            $result['code'] = $code;
        }
        header("Content-Type: application/json; charset=UTF-8");
        exit(json_encode($result));
    }
}

if (!function_exists('fun_img')) {
    /**
     * 拼接系统内图片url
     * @param $img
     * @return string
     */
    function fun_img($img){
        if (empty($img)) {
            return '';
        } elseif(strpos(strtolower($img), 'http://') === 0 || strpos(strtolower($img), 'https://') === 0 ) {
            return $img;
        } else {
            //return env('CDN_URL').$img;
            return 'https://minappcdn.mcdonalds.com.cn'.$img;
        }
    }
}

if (! function_exists('fun_respon_head')) {
    /**
     *  return json maxed
     */
    function fun_respon_head($success, $res = [], $code = 200)
    {
        $result['result'] = $success;

        if ($success) {
            $result['result'] = 1;
            $result['msg'] = '操作成功';
            $result['data'] = $res;
            $result['code'] = 200;
        } else {
            $result['result'] = 0;
            $result['msg'] = $res;
            $result['code'] = $code;
        }
        header("Content-Type: application/json; charset=UTF-8");
        exit(json_encode($result));
    }
}

if (!function_exists('fun_curl')) {
    /**
     * json curl request
     * @param $url
     * @param $data
     * @param $token
     * @return mixed
     */
    function fun_curl($url,$data){
        $ch = curl_init();
        //print_r($ch);
        curl_setopt( $ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时

        if(0 === strpos(strtolower($url), 'https'))
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
        }
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, ['Content-Type:text/xml'] );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }

}

if (!function_exists('fun_curl_header')) {
    /**
     * json curl request
     * @param $url
     * @param $data
     * @param $token
     * @return mixed
     */
    function fun_curl_header($url,$data, $header=['Content-Type:application/json']){
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时

        if(0 === strpos(strtolower($url), 'https'))
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
        }
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }

}


if (!function_exists('sendTemplate')) {
    /**
     *  发送模板消息
     */
    function sendTemplate($openid,$data,$template_id,$page='pages/home/home'){
        $formId = DB::table('user_formid')->where(['openid'=>$openid])->orderBy('id', 'desc')->first();
        //$formId = user_formid::lastformid($openid);
        if (!$formId) {
            savelog('no_push_user', 'openid=' . $openid);
            return 'exit';
        }
        $res = WxSmallClient::sendTemplate($openid, $data, $formId->form_id, $template_id, $page);
        if (!isset($res['errcode']) || $res['errcode'] != 0) {
            savelog('push_err_log', json_encode($res) . 'openid=' . $openid . '&form_id=' . $formId->form_id);
        }
        // 删除用过的form_id
        DB::table('user_formid')->where('id', $formId->id)->delete();
    }
}

if (!function_exists('arrayToXml')) {
    /**
     *  作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key=>$val) {
            if (is_numeric($val)) {
                $xml.="<".$key.">".$val."</".$key.">";
            } else {
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
}

if (!function_exists('xmlToArray')) {
    /*
     * xml转换数组
     */
    function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
}

if (!function_exists('fun_curl_get')) {
    /**
     * json curl request
     * @param $url
     * @param $data
     * @param $token
     * @return mixed
     */
    function fun_curl_get($url){
        $ch = curl_init();
        //print_r($ch);
        curl_setopt( $ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时

        if(0 === strpos(strtolower($url), 'https'))
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
        }
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }

}

if (!function_exists('fun_error_view')) {
    /**
     * json curl request
     * @param $url
     * @param $data
     * @param $token
     * @return mixed
     */
    function fun_error_view($code, $content, $url){
        if ($code == 0) {
            return view('admin.error')->with('info', ['error'=>$content, 'url'=>$url]);
        } else {
            return view('admin.error')->with('info', ['success'=>$content, 'url'=>$url]);
        }
    }

}


if (!function_exists('aes_decryptString')) {
    /**
     *  aes 解码手机号
     */
    function aes_decryptString($str,$key='827b35a782d85721e19b345c74343e9b'){
        $str = base64_decode($str);
        $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
        $block = mcrypt_get_block_size('rijndael_128', 'ecb');
        $pad = ord($str[($len = strlen($str)) - 1]);
        $len = strlen($str);
        $pad = ord($str[$len-1]);
        $de_txt = substr($str, 0, strlen($str) - $pad);
        return  substr($de_txt, 0, 11);
    }
}

if (!function_exists('eachplue_curl')) {
    /**
     *  趋佳通用请求接口
     */
    function eachplue_curl($url, $body){
        //$url = env('EACH_URL').'/api/queryByUid';
        $sign_str = $url.json_encode($body).env('EACH_KEY');
        $sign = hash('sha256', $sign_str);
        $header = [
            'X-EACH-VENDOR-ID:'.env('EACH_VENDORID','106'),
            'X-EACH-APP-ID:'.env('EACH_APPID','points'),
            'X-EACH-SIGNATURE:'.$sign
        ];
        $start_time = round(microtime(true)*1000);
        $qujia_res = Curl::to( $url )
            ->withContentType('application/json')
            ->withHeader('X-EACH-VENDOR-ID: '.env('EACH_VENDORID','106'))
            ->withHeader('X-EACH-APP-ID: '.env('EACH_APPID','points'))
            ->withHeader('X-EACH-SIGNATURE: '.$sign)
            ->withData( $body )
            ->asJsonRequest()
            ->post();
        $end_time = round(microtime(true)*1000);
        $use_time = $end_time-$start_time;
        if ($use_time > 3000) {
            Storage::disk('public')->append('timeout_eachplue.log', 'time:'.date('Y-m-d H:i:s').'  use_time:'.$use_time.'  url:'.$url, '  params:'.json_encode($body));
        }
        $res = json_decode($qujia_res, true);
        return $res;
    }
}


if (!function_exists('savelog')) {
    function savelog($filename, $logdata)
    {
        // 文件路径 storage/app/log
        Storage::disk('public')->append($filename, 'time:'.date('Y-m-d H:i:s')."\nresponse:".$logdata);
    }
}

if (!function_exists('fun_uinfo'))
{
    function fun_uinfo($unionid)
    {
        if (empty($unionid)) {
            return false;
        }
        $hash_key = 'uinfo_'.$unionid;
        $uinfo = Redis::get($hash_key);
        if ($uinfo) {
            return json_decode($uinfo, 1);
        } else {
            $uinfo = mcds_users::select('id', 'phone', 'nickname', 'wb_id', 'openid', 'unionid', 'avatar_url','send_time')
                ->where('unionid',$unionid)->first();
            if ($uinfo) {
                $uinfo = $uinfo->toArray();
                Redis::setex($hash_key, 7200, json_encode($uinfo));
                return $uinfo;
            } else {
                return false;
            }
        }
    }
}


/**
 * 获取本周开始和结束时间
 */
if (!function_exists('get_weektime'))
{
    function get_weektime()
    {
        $sdefaultDate = date("Y-m-d");
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w=date('w',strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w : 6).' days')).' 00:00:00';
//        $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - 1 : 6).' days')).' 00:00:00';
        //本周结束日期
        $week_end=date('Y-m-d',strtotime("$week_start +6 days")).' 23:59:59';
        if($sdefaultDate >= '2018-06-17 00:00:00')
        {
            $week_start = '2018-06-17 00:00:00';
            $week_end = '2018-06-18 23:59:59';
        }
        return ['week_start'=>$week_start, 'week_end'=>$week_end];
    }
}

if (!function_exists('get_luck_card')) {
    function get_luck_card()
    {
        $timeOver = [];
        if (time() < strtotime('2018-06-02 23:59:00')) {
            $timeOver = ['pVI6xjjC-23euBULvLP-NJ58p3jc', 'pVI6xjtZqJPRXzqpS0NBrnBgzRAo'];
        }
        $noChange = [
            'pVI6xjv-KOQfpsNsaLft4vgtDlJk',
            'pVI6xjsBCD7YertSeaHiKvZsP57M',
            'pVI6xjoRwvWGj3QWNZwz9G7gFlUM',
            'pVI6xjjO2g-i3ZlZgBfmvBaM0ju8',
            'pVI6xjtSswwMUtNLwZIpY8zZLxLE',
            'pVI6xjgT1ggdgCFxJQBwiZojzDtM',
            'pVI6xjqT2ybsq8K-E29ayHMtCt2A',
            'pVI6xjpxfJFNShi4ZuzMQqjr4dE8',
            'pVI6xjmhHX4_nasljrjTSGxo03qc',
            'pVI6xjgJReNFOoeC4JTp9_TAm_1I',
            'pVI6xjjO9v_HnJNznN_eEH1CbQDE',
            'pVI6xjt6MKhtuOiMxsYJn8LXd5oM',
            'pVI6xjmTHE17_HNdXsBCTdZKNV74',
            'pVI6xjiBqbDd1-1sMeUwfq1XoL60',
            'pVI6xjk1-szoJvthNoEkG35escvk',
            'pVI6xjpz7yNrYKnWL6p8jnJyAXFU',
        ];
//        if(env('debug_time_513',0) == 1)
//        {
//           $noChange = [
//            'pVI6xjp6QqrJFgWC_tGkcQEDNz1w',
//            'pVI6xjpz7yNrYKnWL6p8jnJyAXFU',
//           ];
//        }
        $newNoChange = array_merge($timeOver, $noChange);
        return $newNoChange;
    }
}

/**
 * 选手系统投票密码
 */
if (!function_exists('get_player_pass')) {
    function get_player_pass($player_id,$pass)
    {
        if($player_id <0 || $player_id > 100)
        {
            return false;
        }
        $playerPass = [
            '24'=>'123456',
            '2'=>'123456',
            '3'=>'123456',
            '4'=>'123456',
            '5'=>'123456',
            '6'=>'123456',
        ];
        if(isset($playerPass[$player_id]) &&  $playerPass[$player_id] == $pass)
        {
            return true;
        }
        return false;
    }
}

/**
 * 选手列表对应卡ID和城市
 */
if (!function_exists('get_player_card')) {
    function get_player_card($player_id=0)
    {
        $cardInfo = [
            '61'=>[
                'card_id'=>'pVI6xjvzsBHYmzTOnRFem5fAKJA8',      // 积分的
                'card_lucky'=>'pVI6xjv_ciqNAZTKt_t5UYzMlfyE', // 抽奖的
                'lucky_num'=>10, // 抽几个中奖用户
                'city'=>'杭州',
                'meet_date'=>'06-08 20:00-21:00',
                'type'=>1,
                'num'=>60,
                'err'=>0
            ]/*,
            '59'=> [
                'card_id'=>'pVI6xjsT8elGOIeM63qdXdQ_quy0',
                'card_lucky'=>'pVI6xjkM8T-TZiTq_-mvqQb82UTg',
                'lucky_num'=>20,
                'city'=>'苏州',
                'meet_date'=>'05-25 18:00-20:00',
                'type'=>1,
                'num'=>100,
                'err'=>1
            ],
            '3'=>[
                'card_id'=>'card_id3',
                'city'=>'city_3',
                'meet_date'=>'meet_date_3',
                'type'=>1,
                'err'=>1
            ],*/
        ];
        if(!isset($cardInfo[$player_id]))
        {
            $re = ['card_id'=>NULL,'city'=>NULL,'meet_date'=>NULL,'type'=>NULL,'err'=>1];
        }else
        {
            $re = $cardInfo[$player_id];
        }
        return $re;
    }
}


if (!function_exists('getFirstChart')) {
    function getFirstChart($str)
    {
        if (empty($str)) {
            return '';
        }
        $char = ord($str[0]);
        if ($char >= ord('A') && $char <= ord('z')) {
            return strtoupper($str[0]);
        }
        $s1 = iconv('UTF-8', 'GB2312//IGNORE',  $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) return 'A';
        if ($asc >= -20283 && $asc <= -19776) return 'B';
        if ($asc >= -19775 && $asc <= -19219) return 'C';
        if ($asc >= -19218 && $asc <= -18711) return 'D';
        if ($asc >= -18710 && $asc <= -18527) return 'E';
        if ($asc >= -18526 && $asc <= -18240) return 'F';
        if ($asc >= -18239 && $asc <= -17923) return 'G';
        if ($asc >= -17922 && $asc <= -17418) return 'H';
        if ($asc >= -17417 && $asc <= -16475) return 'J';
        if ($asc >= -16474 && $asc <= -16213) return 'K';
        if ($asc >= -16212 && $asc <= -15641) return 'L';
        if ($asc >= -15640 && $asc <= -15166) return 'M';
        if ($asc >= -15165 && $asc <= -14923) return 'N';
        if ($asc >= -14922 && $asc <= -14915) return 'O';
        if ($asc >= -14914 && $asc <= -14631) return 'P';
        if ($asc >= -14630 && $asc <= -14150) return 'Q';
        if ($asc >= -14149 && $asc <= -14091) return 'R';
        if ($asc >= -14090 && $asc <= -13319) return 'S';
        if ($asc >= -13318 && $asc <= -12839) return 'T';
        if ($asc >= -12838 && $asc <= -12557) return 'W';
        if ($asc >= -12556 && $asc <= -11848) return 'X';
        if ($asc >= -11847 && $asc <= -11056) return 'Y';
        if ($asc >= -11055 && $asc <= -10247) return 'Z';
        return null;
    }
}
if (!function_exists('chartSort')) {
    function chartSort($user)
    {
        foreach ($user as $k => &$v) {
            $v['chart'] = getFirstChart($v['player_name']);
//                $v['player_name'] = iconv('UTF-8', 'GB2312//IGNORE',$v['player_name']);
        }
        $data = [];
        foreach ($user as $k => $v) {
            if (empty($data[$v['chart']])) {
                $data[$v['chart']] = [];
            }
            $data[$v['chart']][] = $v;
        }
        ksort($data);
        return $data;
    }
}

if (!function_exists('isValidMobile')) {
    function isValidMobile($mobile){
        return preg_match("/^1[34578]{1}\d{9}$/",$mobile);
    }
}


if (!function_exists('object_array')) {
    function object_array($array)
    {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
        return $array;
    }
}


if (!function_exists('add_bonus_record')) {
    function add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,$species,$remark='')
    {
        $data['openid'] = $openid;
        $data['before_bonus'] = $before_bonus;
        $data['change_bonus'] = $change_bonus;
        $data['after_bonus'] = $after_bonus;
        $data['status'] = $status;
        $data['type'] = $type;
        $data['species'] = $species;
        $data['remark'] = $remark;
        DB::table('member_bonus_record')->insert($data);

    }
}


if (!function_exists('get_member')) {
    function get_member($openid)
    {
        $member_info = DB::table('member')->where(['openid'=>$openid])->first();
        return $member_info;
    }
}


if (!function_exists('get_level')) {
    function get_level($total_bonus,$consume_bonus)
    {
        if ($total_bonus>=3000 && $consume_bonus>=1000){
            return 3;  //女王/陛下
        }elseif($total_bonus>=1000){
            return 2;  //王妃/伯爵
        }elseif($total_bonus>=300){
            return 1;  //小公主/小王子
        }else{
            return 0;  //小主
        }

    }
}


if (!function_exists('frozen_money')) {
    function frozen_money($user_id,$order_id,$money,$type)
    {
        //查询账户情况
        $user_frozen_account = DB::table('user_frozen_account')->where(['user_id'=>$user_id])->first();
        $before_money = $user_frozen_account->total_money;
        $change_money = ($money);
        $after_money = $type==1?$before_money+$change_money:$before_money-$change_money;
        $species = 2;
        DB::table('money_record')->insertGetId(['user_id'=>$user_id,'before_money'=>$before_money,'change_money'=>$change_money,"after_money"=>$after_money,'type'=>$type,"species"=>$species,"order_id"=>$order_id,'created_at'=>date('Y-m-d H:i:s',time())]);
        DB::table('user_frozen_account')->where(['user_id'=>$user_id])->update(['total_money'=>$after_money]);
    }
}


if (!function_exists('account_money')) {
    function account_money($user_id,$order_id,$money,$type)
    {
        //查询账户情况
        $user_frozen_account = DB::table('user_account')->where(['user_id'=>$user_id])->first();
        $before_money = $user_frozen_account->total_money;
        $change_money = $money;
        $after_money = $type==1?$before_money+$change_money:$before_money-$change_money;
        $species = 1;
        DB::table('money_record')->insertGetId(['user_id'=>$user_id,'before_money'=>$before_money,'change_money'=>$change_money,"after_money"=>$after_money,'type'=>$type,"species"=>$species,"order_id"=>$order_id,'created_at'=>date('Y-m-d H:i:s',time())]);
        DB::table('user_account')->where(['user_id'=>$user_id])->update(['total_money'=>$after_money]);
    }
}







